package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Student;
import com.example.demo.entity.Teacher;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IStudentService;
import com.example.demo.service.ITeacherService;
import com.example.demo.service.IUserService;
import com.example.demo.utils.AjaxJson;
import com.example.demo.utils.BCryptUtil;
import com.example.demo.vo.studentAddVo;
import com.example.demo.vo.teacherAddVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author
 * @since 2025-11-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    ITeacherService teacherService;
    @Autowired
    private IStudentService studentService;

    @Override
    public AjaxJson login(String username, String password, Integer roleId) {
        User user = this.getOne(new QueryWrapper<User>().eq("username", username).eq("role_id", roleId));
        if (user == null) {
            return AjaxJson.getError("对应用户不存在");
        } else if (!BCryptUtil.matches(password, user.getPassword())) {
            return AjaxJson.getError("密码错误");
        } else if (user.getStatus() == 0) {
            return AjaxJson.getError("用户未启用，请联系管理员");
        }
        user.setPassword("");
        return AjaxJson.getSuccessData(user);
    }

    @Override
    public AjaxJson updatePassword(String oldPassword, String newPassword, User user) {
        if (user == null || user.getUserId() == null) {
            return AjaxJson.getError("用户信息不完整");
        }
        User dbUser = this.getOne(new QueryWrapper<User>().eq("user_id", user.getUserId()));
        if (dbUser == null) {
            return AjaxJson.getError("用户不存在");
        }
        if (!BCryptUtil.matches(oldPassword, dbUser.getPassword())) {
            return AjaxJson.getError("旧密码错误");
        } else {
            user.setPassword(BCryptUtil.encode(newPassword));
            user.setUpdateTime(LocalDateTime.now());
            return this.updateById(user) ? AjaxJson.getSuccess("修改成功") : AjaxJson.getError("修改失败");
        }
    }

    @Override
    public AjaxJson register(User user) {
        //检验username、password、roleId、realName不能为空
        if (user.getUsername() == null || user.getUsername().isEmpty() || user.getPassword() == null || user.getPassword().isEmpty() || user.getRoleId() == null || user.getRealName() == null || user.getRealName().isEmpty()) {
            return AjaxJson.getError("参数不能为空");
        }
        if (user.getRoleId() != 2 && user.getRoleId() != 3) {
            return AjaxJson.getError("角色id错误");
        }
        if (this.getOne(new QueryWrapper<User>().eq("username", user.getUsername())) != null) {
            return AjaxJson.getError("用户名已存在");
        }

        // 处理gender字段，确保其符合数据库枚举值要求
        if (user.getGender() == null ||
                (!"男".equals(user.getGender()) && !"女".equals(user.getGender()) && !"未知".equals(user.getGender()))) {
            user.setGender("未知"); // 默认值
        }
        if (user.getPhone() == null) {
            user.setPhone("");
        }
        if (user.getEmail() == null) {
            user.setEmail("");
        }
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());


        user.setPassword(BCryptUtil.encode(user.getPassword()));

        // 先保存用户信息
        if (!this.save(user)) {
            return AjaxJson.getError("注册失败");
        }

        // 如果用户是学生，需要添加到学生表，如果是教师，需要添加到教师表
        if (user.getRoleId() == 2) {
            Teacher teacher = new Teacher();
            teacher.setUserId(user.getUserId());
            teacher.setCreateTime(LocalDateTime.now());
            teacher.setUpdateTime(LocalDateTime.now());
            teacherService.save(teacher);
        } else if (user.getRoleId() == 3) {
            Student student = new Student();
            student.setUserId(user.getUserId());
            student.setCreateTime(LocalDateTime.now());
            student.setUpdateTime(LocalDateTime.now());
            studentService.save(student);
        }


        return AjaxJson.getSuccessData(user);
    }

    @Override
    public AjaxJson approve(Integer id) {
        User userId = this.getOne(new QueryWrapper<User>().eq("user_id", id));
        if (userId == null) {
            return AjaxJson.getError("用户不存在");
        } else if (userId.getStatus() == 1) {
            return this.update(new User().setStatus(0), new QueryWrapper<User>().eq("user_id", id)) ? AjaxJson.getSuccess("审核成功") : AjaxJson.getError("审核失败");
        } else {
            return this.update(new User().setStatus(1), new QueryWrapper<User>().eq("user_id", id)) ? AjaxJson.getSuccess("审核成功") : AjaxJson.getError("审核失败");

        }
    }

    @Override
    public AjaxJson addRegisterByStudent(studentAddVo student) {

        User user = new User();
        user.setUsername(student.getUsername());
        user.setPassword(student.getPassword());
        user.setRoleId(3);
        user.setRealName(student.getRealName());
        user.setGender(student.getGender());
        user.setPhone(student.getPhone());
        user.setEmail(student.getEmail());
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        return this.register(user);
    }

    @Override
    public AjaxJson addRegisterByTeacher(teacherAddVo teacher) {
        User user = new User();
        user.setUsername(teacher.getUsername());
        user.setPassword(teacher.getPassword());
        user.setRoleId(2);
        user.setRealName(teacher.getRealName());
        user.setGender(teacher.getGender());
        user.setPhone(teacher.getPhone());
        user.setEmail(teacher.getEmail());
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        return this.register(user);
    }

//    @Override
//    public AjaxJson updateByTeacher(teacherAddVo teacher) {
//
//    }
}